package com.gamenew.bluetoothdemo.ui.activity;

import android.Manifest;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.conn.BleCharacterCallback;
import com.clj.fastble.data.ScanResult;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.gamenew.bluetoothdemo.R;
import com.gamenew.bluetoothdemo.data.BleTcp;
import com.gamenew.bluetoothdemo.service.BluetoothService;
import com.gamenew.bluetoothdemo.ui.BaseActivity;
import com.gamenew.bluetoothdemo.widget.RankingPopupWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class IndexActivity extends BaseActivity {

    @BindView(R.id.tv_environment)
    TextView tvEnvironment;
    @BindView(R.id.tv_body)
    TextView tvBody;
    @BindView(R.id.tv_mt_temp)
    TextView tvMtTemp;
    @BindView(R.id.tv_mt_adjust)
    TextView tvAdjust;
    @BindView(R.id.tv_battery1)
    TextView tvBattery1;
    @BindView(R.id.tv_battery2)
    TextView tvBattery2;
    @BindView(R.id.btn_drive_close)
    Button mBtnClose;
    @BindView(R.id.btn_temp_add)
    Button mBtnAdd;
    @BindView(R.id.btn_temp_subtract)
    Button mBtnSubtract;
    @BindView(R.id.iv_bluetooth)
    ImageView mIvDevice;
    @BindView(R.id.iv_mt)
    ImageView mIvThermometer;
    @BindView(R.id.iv_play_music)
    ImageView mIvMusic;


    private BluetoothService mBluetoothService;
    private List<ScanResult> mList = new ArrayList<>();

    //标记是否连接蓝牙
    private boolean isConnected = false;

    //加减温度
    private int mPage = 0;

    //开关机拼接结尾字符串
    private String mEnd;
    private String mTiaoJieEnd;
    private static ScanResult mScanResult;//保存这个蓝牙设备结果，用于断线重连

    ///各种状态信息
    private String state1, state2, state3, state4, state5, state6, state7;


    @Override
    protected int setResourcesId() {
        return R.layout.activity_index;
    }

    @Override
    protected void initView() {
        super.initView();
        initDialog();
    }

    public static void actionActivity(Context context) {
        Intent intent = new Intent(context, IndexActivity.class);
        context.startActivity(intent);
    }

    @OnClick({R.id.btn_drive_close, R.id.btn_temp_add, R.id.btn_temp_subtract, R.id.iv_bluetooth, R.id.iv_play_music})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.btn_drive_close:
                if (isConnected && "01".equals(state1)) {
                    writeBle(3, "7300" + mEnd);
                } else if (isConnected && "00".equals(state1)) {
                    writeBle(3, "7301" + mEnd);
                }
                break;
            case R.id.btn_temp_add:///+
                if (isConnected) {
                    mPage++;
                    if (mPage < 10) {
                        writeBle(1, "73010" + mPage + mTiaoJieEnd);
                    } else if (mPage > 9) {
                        writeBle(1, "7301" + mPage + mTiaoJieEnd);
                    }
                }
                break;
            case R.id.btn_temp_subtract:///-
                if (isConnected) {
                    mPage--;
                    if (mPage < 10) {
                        writeBle(2, "73010" + mPage + mTiaoJieEnd);
                    } else if (mPage > 9) {
                        writeBle(2, "7301" + mPage + mTiaoJieEnd);
                    }
                }
                break;
            case R.id.iv_bluetooth:
                initListItem();
                checkPermissions();
                break;
            case R.id.iv_play_music:
                //音乐播放器
                MusicActivity.actionActivity(IndexActivity.this);
                break;
        }
    }

    private RankingPopupWindow mWindow;
    private RankingPopupWindow.Listener listener;

    private void initListItem() {
        //生成Listener和清空
        setPopupWindowListener();
        mWindow = null;
        //显示popupwindow
        mWindow = new RankingPopupWindow(this, mList, listener, mIvDevice);
    }

    private void setPopupWindowListener() {
        listener = null;
        listener = new RankingPopupWindow.Listener() {
            @Override
            public void onPopupWindowDismissListener() {
                //消失时的操作
            }

            @Override
            public void onItemClickListener(int position) {
                //点击Item时的操作，连接蓝牙
                if (mBluetoothService != null) {
                    mScanResult = mList.get(position);

                    mBluetoothService.cancelScan();
                    mBluetoothService.connectDevice(mList.get(position));//连接蓝牙
                    mList.clear();
                }
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBluetoothService != null)
            unbindService();
    }

    /**
     * 绑定服务
     */
    private void bindService() {
        Intent bindIntent = new Intent(this, BluetoothService.class);
        this.bindService(bindIntent, mFhrSCon, Context.BIND_AUTO_CREATE);
    }

    /**
     * 解绑服务
     */
    private void unbindService() {
        this.unbindService(mFhrSCon);
    }


    private ServiceConnection mFhrSCon = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBluetoothService = ((BluetoothService.BluetoothBinder) service).getService();
            mBluetoothService.setScanCallback(callback);
            mBluetoothService.scanDevice();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBluetoothService = null;
        }
    };


    /**
     * 蓝牙搜索回调
     */
    private BluetoothService.Callback callback = new BluetoothService.Callback() {
        @Override
        public void onStartScan() {//开始搜索
            mList.clear();
            mWindow.mAdapter.notifyDataSetChanged();
        }

        @Override
        public void onScanning(ScanResult result) {//搜索中
            mList.add(result);
            mWindow.mAdapter.notifyDataSetChanged();

            Log.i("bluetooth", "onScanning: " + result.getDevice().getAddress());
        }

        @Override
        public void onScanComplete() {//搜索完成
            showToast("搜索完成");
        }

        @Override
        public void onConnecting() {//连接中
            showProgressDialog("蓝牙连接中...");
        }

        @Override
        public void onConnectFail() {
            dismissProgressDialog();
            showToast("连接失败");
        }

        @Override
        public void onDisConnected() {
            mList.clear();
            mWindow.mAdapter.notifyDataSetChanged();
            showToast("连接断开");

            isConnected = false;

            mIvDevice.setImageResource(R.mipmap.icon_bluetooth_off);
            mIvThermometer.setImageResource(R.mipmap.icon_thermometer_off);
            mIvMusic.setVisibility(View.GONE);

            showProgressDialog("断线重连中...");
            reconnection();
        }

        @Override
        public void onServicesDiscovered() {//连接完成
            dismissProgressDialog();
            showToast("连接成功");

            subscibeNotify();//订阅通知

            isConnected = true;

            mIvDevice.setImageResource(R.mipmap.icon_bluetooth);
            mIvThermometer.setImageResource(R.mipmap.icon_thermometer);
            mIvMusic.setVisibility(View.VISIBLE);
        }
    };

    /**
     * 连接成功，订阅蓝牙的通知
     */
    private void subscibeNotify() {
        mBluetoothService.notify(BleTcp.SERVICE_UUID, BleTcp.NOTIFY_UUID, new BleCharacterCallback() {
            @Override
            public void onSuccess(BluetoothGattCharacteristic characteristic) {
                String text = String.valueOf(HexUtil.encodeHex(characteristic.getValue()));//拿到数据，解析数据

                Log.i("blue--", "onSuccess: " + text);

                parse(text);//解析数据

            }

            @Override
            public void onFailure(BleException exception) {
                showToast("订阅失败" + exception.toString());
            }

            @Override
            public void onInitiatedResult(boolean result) {
                showToast("订阅成功");
            }
        });
    }

    //解析蓝牙传回来的数据
    private void parse(String text) {

        mEnd = text.substring(4, text.length());
        mTiaoJieEnd = text.substring(6, text.length());


        Log.i("结尾", "parse: " + mTiaoJieEnd);

        state1 = text.substring(2, 4);//开关机
        state2 = text.substring(4, 6);//调节冷敷器温度参数
        state3 = text.substring(6, 8);//冷敷器温度
        state4 = text.substring(8, 10);//人体
        state5 = text.substring(10, 12);//环境
        state6 = text.substring(12, 14);//电池1
        state7 = text.substring(14, 16);//电池2

        mPage = Integer.parseInt(state2);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvBody.setText(state4 + "°C");
                tvEnvironment.setText(state5 + "°C");
                tvMtTemp.setText(state3 + "°C");
                tvAdjust.setText(state2 + "°C");

                tvBattery1.setText("1电池电量：" + Integer.parseInt(state6, 16) + "%");
                tvBattery2.setText("2电池电量：" + Integer.parseInt(state7, 16) + "%");

                //开关机状态
                if ("00".equals(state1)) {
                    mBtnClose.setBackgroundResource(R.mipmap.icon_close_off);
                } else {
                    mBtnClose.setBackgroundResource(R.mipmap.icon_close);
                }
            }
        });

        Log.i("电池1", "parse: " + state6);
        Log.i("电池2", "parse: " + state7);

    }

    /**
     * 蓝牙写操作
     */
    private void writeBle(final int flag, String text) {
        mBluetoothService.write(BleTcp.SERVICE_UUID, BleTcp.WRITE_UUID, text, new BleCharacterCallback() {
            @Override
            public void onSuccess(BluetoothGattCharacteristic characteristic) {
                showToast("写入成功");
            }

            @Override
            public void onFailure(BleException exception) {
                showToast("操作失败了，请重新操作");
            }

            @Override
            public void onInitiatedResult(boolean result) {
//                if (result && flag == 1) {
//                    mPage++;
//                } else if (result && flag == 2) {
//                    mPage--;
//                }
            }
        });
    }

    /**
     * 蓝牙读操作
     * 未分配读特征码
     */
    private void readBle() {
        mBluetoothService.read(BleTcp.SERVICE_UUID, "", new BleCharacterCallback() {
            @Override
            public void onSuccess(BluetoothGattCharacteristic characteristic) {
                String text = String.valueOf(HexUtil.encodeHex(characteristic.getValue()));
            }

            @Override
            public void onFailure(BleException exception) {
                showToast("读取数据失败了" + exception.toString());
            }

            @Override
            public void onInitiatedResult(boolean result) {

            }
        });
    }

    /**
     * 断线重连
     */
    private void reconnection() {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mBluetoothService.connectDevice(mScanResult);
            }
        }, 800);
    }


    /**
     * 动态权限申请
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */

    @Override
    public final void onRequestPermissionsResult(int requestCode,
                                                 @NonNull String[] permissions,
                                                 @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 12:
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            onPermissionGranted(permissions[i]);
                        }
                    }
                }
                break;
        }
    }

    private void checkPermissions() {
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, 12);
        }
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (mBluetoothService == null) {
                    bindService();
                } else {
                    mBluetoothService.scanDevice();
                }
                break;
        }
    }

}
